<template>
  <el-dialog title="用户信息" v-model="visible" @update:model-value="close()">
    <pf-form
      ref="userFormRef"
      @changeEvent="userFormRefChange"
      :config="userFormConfig"
      :model="userInfo"
    ></pf-form>
    <template #footer>
      <div class="pf-text-right">
        <el-button type="primary" @click="confirmCreateUser">确认</el-button>
        <el-button @click="close()">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref, Ref, toRefs, watch } from 'vue';
import { emptyForm, emptyTable, FormModel, TableModel, useAuth, useData } from 'pf-component';
import { TNode, useOrg } from '@/views/system/org/use-org';
import { useNotice } from '@/components/element-plus/notice';
import { FormNameEnum } from '@/constants/enum/form-name.enum';
import { useGuest } from '@/views/system/guest/use-guest';

export default defineComponent({
  name: 'UserInfoDialog',
  props: {
    show: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    userInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    treeData: {
      type: Array,
      default: () => {
        return null; // 若不需要内部查询时，外部可先传个空数组，然后push数据即可（组件内部会跟随变化，因为toRefs(props)是响应式的）
      }
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const { message } = useNotice();
    const { companyTreeList, findNodeById, tNodeToOptions } = useOrg();
    const { registerGuest } = useGuest();
    const { userInfo, treeData } = toRefs(props);
    const show: Ref<boolean> = toRefs(props).show;
    const innerTreeData: Ref<TNode[] | null> = ref(null); // 因为不能修改treeData，定义一个innerTreeData，在外部不传此参数时用到
    const getTreeData = (): TNode[] => {
      if (innerTreeData.value === null) {
        return treeData.value as any;
      }
      return innerTreeData.value;
    };

    const userConfig: Ref<TableModel> = ref(emptyTable);
    const userFormRef = ref(null);
    const userFormConfig: Ref<FormModel> = ref(emptyForm);
    onMounted(() => {
      Promise.all([
        useData().loadForm([{ name: FormNameEnum.guest, config: userFormConfig, info: userInfo }])
      ]).then(ress => {
        if (ress.findIndex(res => !res) === -1) {
          if (treeData.value === null) {
            companyTreeList().then(res => {
              innerTreeData.value = res;
            });
          } else {
            Promise.resolve();
          }
        }
      });
    });
    const userFormRefChange = (newV: any, prop: string) => {
      if (prop === 'userComId') {
        const node: TNode | undefined = findNodeById(getTreeData(), newV);
        if (node) {
          userFormConfig.value?.setOptions(
            'userDeptId',
            tNodeToOptions(node.children.filter(t => !t.isCom))
          );
        } else {
          userFormConfig.value?.setOptions('userDeptId', []);
        }
      }
    };

    const confirmCreateUser = () => {
      (userFormRef.value as any).validate((val: boolean) => {
        if (val) {
          let promise;
          if (!userInfo.value.userId) {
            promise = registerGuest(userInfo.value);
          } else {
            // TODO wangjie
            useNotice().message.error('待完善');
            return;
            // promise = updUser(userInfo.value);
          }
          promise.then(res => {
            if (res) {
              close(true);
            }
          });
        }
      });
    };
    const cancel = () => {
      emit('close');
    };
    const close = (ok?: boolean) => {
      emit('close', ok);
    };
    const visible = ref(false);
    watch(show, () => {
      visible.value = show.value;
      if (show) {
        // TODO wangjie 给表单赋值userInfo变化，并不能触发change事件，要手动触发下
        const tenId = useAuth().getUserInfo().tenId;
        userFormConfig.value?.setOptions(
          'userComId',
          tNodeToOptions(
            getTreeData().filter((t: any) => t.isCom && t.supId === tenId) as any,
            true
          )
        );

        if (userInfo.value.userId) {
          // 用户修改
          userFormRefChange(userInfo.value.userComId, 'userComId');
        } else {
          // 新增
          // 清空公司，部门的下拉项
        }
      }
    });
    return {
      visible,
      userConfig,
      userFormRef,
      userFormRefChange,
      userFormConfig,
      confirmCreateUser,
      cancel,
      close
    };
  }
});
</script>

<style scoped></style>
